<?php


namespace app\api\controller;


use app\admin\model\express\Subscribe;
use app\admin\model\User;
use app\api\model\OrderAddress;
use app\api\model\PackageAddress;
use app\api\model\Service;
use app\common\controller\Api;
use app\common\model\Category;
use fast\Tree;
use Overtrue\Socialite\FactoryInterface;
use think\Cache;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;

class Order extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['category', 'area','p','p1','p2','p3','packagetrack','packageDetail','findForExpress','sign','yuyuetime','indexImg'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    // 获取商品分类
    public function category()
    {
        $tree = Tree::instance();
        $cateArr = [];
        foreach (collection(Category::order('weigh desc,id desc')->select())->toArray() as $category) {
            $cateArr[] = [
                'id' => $category['id'],
                'pid' => $category['pid'],
                'text' => $category['name']
            ];
        }
        $tree->init($cateArr, 'pid');
        $categorylist = $tree->getCateTreeArray(0);
        $this->success('ok', $categorylist);
    }

    // 获取澳洲地区
    public function area()
    {
        $arealist = Cache::get('arealist', '');
        if (!$arealist) {
            $tree = Tree::instance();
            $areaArr = [];
            foreach (collection(Db::name('area_au')->order('id asc')->select())->toArray() as $area) {
                $areaArr[] = [
                    'id' => $area['id'],
                    'pid' => $area['parent_id'],
                    'text' => $area['name']
                ];
            }
            $tree->init($areaArr, 'pid');
            $arealist = $tree->getCateTreeArray(0);
            Cache::set('arealist', $arealist);
        }

        $this->success('ok', $arealist);
    }

    /**
     * @throws \Exception
     * 预报订单不能为空
     */
    public function forecastorder()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            Db::startTrans();
            try {
                $user_id = $this->auth->id;

                if (!$data['order']['from_express_no']) {
                    $this->error('运单号不能为空');
                }
                $count = Db::name('express_order')->where('from_express_no',$data['order']['from_express_no'])->count();
                if($count>0){
                    $this->error('运单号不能重复');
                }
                $data['order']['is_forecast'] = 'yes';
                $data['order']['user_id'] = $user_id;
                $data['order']['order_no'] = orderOn($user_id);
                $data['order']['createtime'] = time();
                $data['order']['updatetime'] = time();
                $data['order']['status'] = "created";

                $order_id = Db::name('express_order')->insertGetId($data['order']);
                $goodsList = [];
                foreach ($data['goods'] as $goods) {
                    $validate = new \think\Validate([
                        'name|商品名称' => 'require',
                        'category_id|分类' => 'require',
                        'number|数量' => 'require|number',
                        'price|价格' => 'float|number',
                    ]);
                    if (!$validate->check($goods)) {
                        $this->error($validate->getError());
                    }
                    $goodsList[] = [
                        'order_id' => $order_id,
                        'name' => $goods['name'],
                        'category_id' => $goods['category_id'],
                        'brand' => $goods['brand'],
                        'number' => $goods['number'],
                        'price' => $goods['price'],
                        'category_ppindex' => $goods['category_ppindex'] ?? 0,
                        'category_pindex' => $goods['category_pindex'] ?? 0,
                        'category_index' => $goods['category_index'] ?? 0,
                    ];
                }
                $goodsData = model('app\api\model\OrderGoods')->saveAll($goodsList);

                if ($data['order']['is_now']=='yes') {
                    $address = model('app\api\model\Address')->get($data['address_id']);
                    //检查
                    if (!$address) {
                        $this->error('收货地址不存在');
                    }
                    $orderAddress = model('app\api\model\OrderAddress')->get([
                        'order_id' => $order_id,
                        'user_id' => $user_id,
                    ]);
                    if ($orderAddress) {
                        $orderAddress->allowField(true)->save([
                            'order_id' => $order_id,
                            'user_id' => $user_id,
                            'name' => $address['name'],
                            'mobile' => $address['mobile'],
                            'province' => $address['province'],
                            'city' => $address['city'],
                            'area' => $address['area'],
                            'address' => $address['address'],
                            'zip_code' => $address['zip_code'],
                            'province_index' => $address['province_index'],
                            'city_index' => $address['city_index'],
                            'area_index' => $address['area_index'],
                        ]);
                    } else {
                        model('app\api\model\OrderAddress')->allowField(true)->save([
                            'order_id' => $order_id,
                            'user_id' => $user_id,
                            'name' => $address['name'],
                            'mobile' => $address['mobile'],
                            'province' => $address['province'],
                            'city' => $address['city'],
                            'area' => $address['area'],
                            'address' => $address['address'],
                            'zip_code' => $address['zip_code'],
                        ]);
                    }
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('ok');
        }
    }

    // 完善订单
    public function complete()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            file_put_contents('test.txt',json_encode($data,JSON_UNESCAPED_UNICODE));
            Db::startTrans();
            try {
                $id = $data['order']['id'];
                $s = Db::name('express_order')->where('id',$id)->value('status');
                if($s!='created'){
                    $this->error('已经完善过了');
                }
                $data['order']['is_forecast'] = 'no';
                if (!$data['order']['is_now']) {
                    $this->error('是不是立即发货');
                }
                if (!$data['order']['is_now']) {
                    $this->error('是不是立即发货不能为空');
                }
                $user = $this->auth->getUser();
                $user_id = $user['id'];
                if($data['order']['is_now']=='yes'){
                    //成生包裹
                    $packaage_no = orderOn($user_id);
                   $packaage_id =  Db::name('express_package')->insertGetId([
                        'package_no'=>orderOn($user_id),
                        'user_id'=>$user_id,
                        'is_delivery'=>1,
                        'status'=>'complete',
                        'createtime'=>time(),
                        'updatetime'=>time(),
                    ]);
                }
                $order = model('app\api\model\Order')->get([
                    'id' => $data['order']['id'],
                    'user_id' => $user_id
                ]);
                if (in_array($order['status'], ['successpay', 'delivered'])) {
                    $this->error('该订单已支付,不可进行修改');
                }
                $data['order']['status'] = 'complete';
                if($data['order']['is_now']=='yes') {
                    $data['order']['package_id'] = $packaage_id;
                    $data['order']['package_no'] = $packaage_no;
                }
                unset($data['order']['from_express_no']);
                $order->allowField(true)->save($data['order']);
                $goodsList = [];
                model('app\api\model\OrderGoods')->where('order_id', $order->id)->delete();
                foreach ($data['goods'] as $goods) {
                    $validate = new \think\Validate([

                        'name|商品名称' => 'require',
                        'category_id|分类' => 'require',
                        //'brand|品牌' => 'require',
                        //'sku|规格' => 'require',
                        //'weight|商品净含量' => 'require|number',
                        'number|数量' => 'require|number',
                        'price|价格' => 'float|number',
                    ]);
                    if (!$validate->check($goods)) {
                        $this->error($validate->getError());
                    }
                    $goodsList[] = [
                        'order_id' => $order->id,
                        'name' => $goods['name'],
                        'category_id' => $goods['category_id'],
                        'brand' => $goods['brand'],
                        //'sku' => $goods['sku'],
                        //'weight' => $goods['weight'],
                        'number' => $goods['number'],
                        'price' => $goods['price'],
                        'category_ppindex' => $goods['category_ppindex'] ?? 0,
                        'category_pindex' => $goods['category_pindex'] ?? 0,
                        'category_index' => $goods['category_index'] ?? 0,
                        //'index' => $goods['index'],
                        //'unit' => $goods['unit'] ?? 'g',
                        //'description' => $goods['description'] ?? 'g',
                        //'number_unit' => $goods['number_unit'] ?? '个',
                        //'rule_id' => Category::where('id',$goods['category_id'])->value('rule_id')
                    ];
                }
                $goodsData = model('app\api\model\OrderGoods')->saveAll($goodsList);

                if ($data['order']['is_now']=='yes') {
                    $address = model('app\api\model\Address')->get($data['address_id']);
                    if (!$address) {
                        $this->error('收货地址不存在');
                    }
                    $orderAddress = model('app\api\model\OrderAddress')->get([
                        'order_id' => $order->id,
                        'user_id' => $user_id,
                    ]);
                    if ($orderAddress) {
                        $orderAddress->allowField(true)->save([
                            'order_id' => $order->id,
                            'user_id' => $user_id,
                            'name' => $address['name'],
                            'mobile' => $address['mobile'],
                            'province' => $address['province'],
                            'city' => $address['city'],
                            'area' => $address['area'],
                            'address' => $address['address'],
                            'zip_code' => $address['zip_code'],
                            'province_index' => $address['province_index'],
                            'city_index' => $address['city_index'],
                            'area_index' => $address['area_index'],
                        ]);
                    } else {
                        model('app\api\model\OrderAddress')->allowField(true)->save([
                            'order_id' => $order->id,
                            'user_id' => $user_id,
                            'name' => $address['name'],
                            'mobile' => $address['mobile'],
                            'province' => $address['province'],
                            'city' => $address['city'],
                            'area' => $address['area'],
                            'address' => $address['address'],
                            'zip_code' => $address['zip_code'],
                        ]);
                    }

                    $packAddressM = new PackageAddress();
                    $packAddress = $packAddressM->get([
                        'package_id' => $packaage_id,
                        'user_id' => $user_id,
                    ]);
                    if ($packAddress) {
                        $packAddressM->allowField(true)->save([
                            'package_id' => $packaage_id,
                            'user_id' => $user_id,
                            'name' => $address['name'],
                            'mobile' => $address['mobile'],
                            'province' => $address['province'],
                            'city' => $address['city'],
                            'area' => $address['area'],
                            'address' => $address['address'],
                            'zip_code' => $address['zip_code'],
                            'province_index' => $address['province_index'],
                            'city_index' => $address['city_index'],
                            'area_index' => $address['area_index'],
                        ]);
                    } else {
                        $packAddressM = new PackageAddress();$packAddressM->allowField(true)->save([
                            'package_id' => $packaage_id,
                            'user_id' => $user_id,
                            'name' => $address['name'],
                            'mobile' => $address['mobile'],
                            'province' => $address['province'],
                            'city' => $address['city'],
                            'area' => $address['area'],
                            'address' => $address['address'],
                            'zip_code' => $address['zip_code'],
                        ]);
                    }
                }

                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('ok');
        }
        $this->error('请求错误');
    }

    // 我的订单
    public function myOrder()
    {
        $type = $this->request->param('type');//1:未入仓  2:在仓
        if($type==1){
            //未入仓
            $where['order.is_forecast'] = 'yes';//预报订单
            $where['order.status'] = 'created';//没有完善
            $where['order.package_id'] = 0;//没有完善
        }elseif($type==2){
            //在仓
            $where['order.status'] = 'complete';//已经完善
            $where['order.package_id'] = 0;//没有打包
            $where['order.is_now'] = 'no';//不是立即发货
        }elseif($type==3){
            //待完善
            $where['order.status'] = 'created';
            $where['order.is_forecast'] = 'no';
            $where['order.package_id'] = 0;//没有 完善
        }

        $where['order.user_id'] = $this->auth->id;

        $list = model('app\api\model\Order')
            ->with(['address'])->with(['goods'])
            ->where($where)
            //->where('address.name|address.mobile|address.address|address.idcard','like','%'.$keywords.'%')
            ->order('order.updatetime desc')
            ->paginate()->each(function($item,$key){
                $item->createtime = date('Y-m-d H:i:s',$item['createtime']);
                $item->updatetime = date('Y-m-d H:i:s',$item['updatetime']);
                $item->goodlist=array_column($item->goods,'name');
                return $item;
            });

        foreach ($list as $row) {
            $row->getRelation('address')->visible(['name', 'mobile', 'province', 'city', 'area', 'address', 'idcard', 'idcard_front', 'idcard_reverse', 'zip_code']);
          //  $row->getRelation('goods')->visible(['name','brand']);
        }

        foreach ($list as $row) {
           // $row->getRelation('goods')->visible(['name']);
           //   $row->getRelation('goods');
        }
        $this->success('ok', $list);
    }

    /**
     *1.待打包
     *2.待支付
     *3.待发货
     *4.转运中
     *5.已签收
     */
    public function mypackage(){
        $user = $this->auth->id;
        $type = $this->request->post('type',0);
        $where['user_id'] = ['=',$user];
        switch ($type){
            case 1:
                $where['status'] = 'complete'; //已完善
                break;
            case 2:
               // $where['status'] = 'waitingpay';//待支付
                $where['status'] = ['in',['waitingpay','check_pay']];//待支付
               // $where['status'] = ['waitingpay','check_pay'];//待支付
                break;
            case 3:
                $where['status'] = 'successpay';//支付成功, 带签收
                break;
            case 4:
                $where['status'] = 'delivered';//转运中
                break;
            case 5:
                $where['status'] = 'sign';//已签收
                break;
            case 6:
                $where['status'] = 'check_pay';//支付待审核
                break;
            case 0:
                $where['createtime'] = ['>',0];
        }

       $list =  Db::name('express_package')->where($where)->order('createtime desc')->paginate()->each(function ($item,$key)use($type){
           $item['orderlist'] = Db::name('express_order')->where('package_id',$item['id'])->select();
           $item['address'] = Db::name('express_package_address')->field(['name', 'mobile', 'province', 'city', 'area', 'address', 'idcard', 'idcard_front', 'idcard_reverse', 'zip_code'])
               ->where('package_id',$item['id'])->find();
           $item['yuyue_sign_time_status'] = 0;
           if($type == 4){
               $track = Db::name('express_package_track')->where(['state'=>'6','package_id'=>$item['id']])->count();
               if($track && empty($item['yuyue_sign_time'])){
                   $item['yuyue_sign_time_status'] = 1;
               }
           }

           return $item;
       });

        $this->success('',$list);
    }

    // 订单详情
    public function orderDetail()
    {
        $id = $this->request->post('id');
        $order = model('app\api\model\Order')->get($id);
        $goodsData = model('app\api\model\OrderGoods')->where(['order_id' => $id])->select();
        foreach ($goodsData as $goods) {
            $goods['category_name'] = Category::where('id', $goods['category_id'])->value('name');
        }
        $goodsData = collection($goodsData)->toArray();
        $order['goods'] = $goodsData;
        $order['address'] = model('app\api\model\OrderAddress')->where('order_id', $id)->find();
        $order['service'] = model('app\api\model\Service')->where('id', 'in', $order['service_ids'])->select();
        $this->success('ok', $order);
    }

    //包裹详情
    public function packageDetail()
    {
        $id = $this->request->param('id',999999999999);
        $express_package = Db::name('express_package')->find($id);
        //状态:0=已入库,1=已预报,2=包裹已出库,3=正在发往澳洲,4=包裹清关中,5=包裹清关完成，等待发往指定地点,6=包裹已抵达指定自提点，等待顾客取件,7=已签收

        if($express_package['state']==0){
            $express_package['state_text'] = '已入库';
        }elseif ($express_package['state']==1){
            $express_package['state_text'] = '已预报';
        }elseif ($express_package['state']==2){
            $express_package['state_text'] = '包裹已出库';
        }elseif ($express_package['state']==3){
            $express_package['state_text'] = '正在发往目的地';
        }elseif ($express_package['state']==4){
            $express_package['state_text'] = '包裹清关中';
        }elseif ($express_package['state']==5){
            $express_package['state_text'] = '包裹清关完成';
        }elseif ($express_package['state']==6){
            $express_package['state_text'] = '包裹已抵达目的地';
        }elseif ($express_package['state']==7){
            $express_package['state_text'] = '已签收';
        }


        $express_package_address = Db::name('express_package_address')->where('package_id',$id)->find();
        $express_package['address'] = $express_package_address;
        $express_order = Db::name('express_order')->where('package_id',$id)->select();

        $order_goods = [];
        $orderlist = [];
        foreach ($express_order as $key=>$value){
          //  $express_order['goods'] = $this->getorderdetail($value['id']);
            $orderlist[] = $this->getorderdetail($value['id']);
            $order_goods = array_merge($order_goods,$this->getorderdetail($value['id'])['goods']);
            foreach ($order_goods as &$g){
                $service_ids = Db::name('express_order')->where('id',$g['order_id'])->value('service_ids');
                $ser =Service::where('id','in',$service_ids)->field('name,price')->select();
                $g['service_text'] = $ser;
              //  $g['createtime'] = date('Y-m-d H:i:s',intval($g['createtime']));
            }

         //   $express_order[$key]['aaaaaaaaaaaaaaaaaaa'] = date('Y-m-d H:i:s',$value['createtime']);
        }

       // $express_package['orderlist'] = $orderlist;
        $express_package['goods'] = $order_goods;
        $this->success('',$express_package);

    }

    //获取订单详情
    protected  function getorderdetail($order_id){
        $order = model('app\api\model\Order')->get($order_id);
        $goodsData = model('app\api\model\OrderGoods')->where(['order_id' => $order_id])->select();
        foreach ($goodsData as $goods) {
            $goods['category_name'] = Category::where('id', $goods['category_id'])->value('name');
        }
        $goodsData = collection($goodsData)->toArray();
        $order['goods'] = $goodsData;
        $order['address'] = model('app\api\model\OrderAddress')->where('order_id', $order_id)->find();
        $order['service'] = model('app\api\model\Service')->where('id', 'in', $order['service_ids'])->select();
        return $order;
    }

    //增值服务列表
    public function serviceList()
    {
        $list = Service::where('status', 'normal')->select();
        $this->success('ok', $list);
    }

    // 添加订单,录单
    public function add()
    {
        if ($this->auth->isworker == 0) {
            $this->error('您无权进行此操作');
        }
        $params['user_id'] = Db::name('user')->where('member_id',$this->request->post('user_id'))->value('id');
        $params['from_express_no'] = $this->request->post('from_express_no');
        $user = User::get($params['user_id']);
        if (!$user) {
            $this->error('该用户不存在1');
        }
        $result = model('app\api\model\Order')->where(['from_express_no'=>$params['from_express_no'],'user_id'=>$params['user_id']])->find();
        if($result){
            if($result['is_forecast'] =='yes'){
                $this->error('该单号已经被预报');
            }else{
                $this->error('该单号已经被添加');
            }
        }


        /*$ehund = new Ehund(Config::get('site.secretKey'), '');
        $number = $ehund->autonumber($params['from_express_no']);*/
        $params['from_express_name'] = '';
        $params['order_no'] = orderOn($params['user_id']);
        $volume = $this->request->param('volume');
        $weight = $this->request->param('weight');
        $result = false;
        $result = model('app\api\model\Order')->allowField(true)->save($params);
        if ($result !== false) {
            $subscribe = new Subscribe();
            $template_id = 'dKj4vly11Mg1C-JRd1a9Z9Jl8qPHh2a46D90eSjMEaE';  //订单状态更新提醒
            $order = Db::name('express_order')->where('from_express_no',$this->request->post('from_express_no'))->find();
            $page = 'pages/IndexServer/AddPackage/AddPackage?form_express='. model('app\api\model\Order')->from_express_no."&orderid=".$order['id'].'&'.'type=complete';
            //$string = '包裹已入库，重量：'.$weight.'KG，体积重： '.$volume.'KG';
            $data = [
                'character_string1' => [
                    'value' => model('app\api\model\Order')->from_express_no
                ],
                'phrase2' => [
                    'value' => "包裹已入库"
                ],
                'thing4' => [
                    'value' => "包裹已入库，如未完善快递信息，请立即填写"
                ],
                'time3' => [
                    'value' => date("Y-m-d H:i:s")
                ]
            ];
            $subscribe=$subscribe->push($params['user_id'], $template_id, $page, $data);
            $this->success("成功");
        } else {
            $this->error(__('No rows were inserted'));
        }
    }

    // 称重&设置支付金额
    public function setWeight()
    {
        if ($this->auth->isworker == 0) {
            $this->error('您无权进行此操作');
        }
        $from_express_no = $this->request->post('from_express_no');
        $params['delivery_weight'] = $this->request->post('delivery_weight');
        $params['delivery_price'] = $this->request->post('delivery_price');
        $order = Db::name('express_package')->where('package_no',$from_express_no)->find();
        if (!$order) {
            $this->error('该订单不存在');
        }
        if ($order['state'] != '6') {
            $this->error('操作失败');
        }

        $result = false;
        $params['status'] = 'waitingpay';
        $result = Db::name('express_package')->where('package_no',$from_express_no)->update($params);
        if ($result !== false) {
            $subscribe = new Subscribe();
           // $template_id = Config::get('site.new_order');
            $template_id = '9bQN97-6b-XflU3TrUKS4FSNyr_tM1SdaM6njkuB1p4';   //订单支付提醒
            $page = 'pages/Packagequery/Packagequery?type=payorder';
            $data = [
                'character_string4' => [
                    'value' => $order['package_no']
                ],
                'amount3' => [
                    'value' => sprintf("%.2f",$params['delivery_price'])
                ],
                'thing2' =>"包裹已到达，请支付包裹邮费",
            ];
            $subscribe->push($order['user_id'], $template_id, $page, $data);
            $this->success();
        } else {
            $this->error(__('No rows were inserted'));
        }
    }

    //前端扫码调用
    public function findForExpress()
    {
        $from_express_no = $this->request->post('from_express_no');
        $type = 0;//1:订单 2:包裹
        $page = 'error';

        $express_order = "";
        //处理包裹号
        if(strncmp($from_express_no,"AD",2) == 0){
            //是包裹单号
            $express_order = Db::name('express_package')->where('package_no',$from_express_no)->find();
            if($express_order){
                $type=1;
                if($express_order['status']=='delivered' && $express_order['state']==6){
                    $page = 'weighing';
                }elseif($express_order['state']==6 && $express_order['status']=="successpay"){
                    $page = 'sign';
                }elseif ($express_order['state']==7){
                    $page = 'signed';
                }
            }
        }

        //处理订单逻辑
        if($type==0){
            $express_order = Db::name('express_order')->where('from_express_no',$from_express_no)->find();
            if(empty($express_order)){
                //完善订单
                $page = 'entry';
            }else{
                $type=2;
                if($express_order['package_id']>0){
                    $page='package';//已经打包
                }elseif($express_order['status']=='complete'){
                    $page = "store";
                }elseif($express_order['is_forecast']=='yes'){  //是否预报订单
                    if($express_order['is_now']=='yes'){   //是否立即发货
                        $page='store';
                    }else{
                        //不立即发货，改成complete状态
                        Db::name('express_order')->where('from_express_no',$from_express_no)->update([
                            'status'=>'complete'
                        ]);
                        $page = 'store';
                    }
                }
            }
        }

        $data = [
            'page' => $page,
            'type'=>$type,
            'from_express_no' => $from_express_no,
            'order' => $express_order,
        ];
        $this->success('ok', $data);
    }

    // 前端签收
    public function signFor()
    {
        if ($this->auth->isworker == 0) {
            $this->error('您无权进行此操作');
        }
        $package_no = $this->request->param('from_express_no');
        $image = $this->request->param('image','');
        $remark = $this->request->param('remark','');
        $user_id = $this->auth->id;
        $package = Db::name('express_package')->where('package_no',$package_no)->find();
        if (!$package) {
            $this->error('该包裹不存在');
        }
        if (!($package['status'] == 'successpay' && $package['state'] == '6')) {
            $this->error('该包裹不可操作');
        }
        Db::startTrans();

        try{
            $res = Db::name('express_package')->where('package_no',$package_no)->update([
                'state'=>7,
                'status'=>'sign',
                'image'=>$image,
                'remark'=>$remark
            ]);
            if(empty($res)){
                throw new \Exception("操作失败");
            }

            $track = model('app\admin\model\express\PackageTrack')->where([
                'package_id' => $package['id'],
                'state' => '7'
            ])->find();
            if (empty($track)) {
                $orderTrackData[] = [
                    'package_id' => $package['id'],
                    'state' => '7',
                    'memo' => '',
                    'user_id' => $this->auth->id,
                ];
                model('app\admin\model\express\PackageTrack')->saveAll($orderTrackData);
            }

            $subscribe = new Subscribe();

           /*  $template_id = "dKj4vly11Mg1C-JRd1a9Z9Jl8qPHh2a46D90eSjMEaE"; //订单状态更新提醒
            $page = 'pages/Packagequery/Packagequery';
            $data = [
                'character_string1' => [
                    'value' => $package['package_no']
                ],
                'phrase2' => [
                    'value' => '包裹已签收'
                ],
                'time3' => [
                    'value' => date('Y-m-d H:i:s', time())
                ],
            ];
            $subscribe->push($package['user_id'], $template_id, $page, $data);
           */
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('操作成功');
    }

    // 预约签收
    public function yuyueSign()
    {
        $yueyue_sign_time = $this->request->post('yueyue_sign_time');
        $ids = $this->request->post('ids');
        if(empty($ids)){
            $this->error("缺少参数");
        }
        if(empty($yueyue_sign_time)){
            $this->error("缺少参数");
        }

        $ids_ar = explode(',',$ids);
        $order_list = model('app\admin\model\express\Package')
            ->where('id','in', $ids_ar)
            ->select();
        if (!$order_list) {
            $this->error('该包裹不存在');
        }

        foreach ($order_list as $order){
            if (!($order['status'] == 'delivered' && $order['state'] == '6')) {
                $this->error('该包裹不可操作');
            }
            if($order->yuyue_sign_time){
                $this->error('该包裹已经预约');
            }
            $order->yuyue_sign_time = $yueyue_sign_time;
            if ($order->save()) {
            } else {
                $this->error('操作失败');
            }
        }
        $this->success('操作成功');
    }

    //
    public function lists(){
        $type = $this->request->get('type');//1:未入仓  2:在仓
        if($type==1){
            $where['order.is_forecast'] = 'yes';//预报订单
            $where['order.package_id'] = 0;//没有打成包
            $where['order.status'] = 'created';//没有完善
        }elseif($type==2){
            $where['order.package_id'] = 0;//没有打成包
            $where['order.status'] = 'complete';//已经完善
            $where['order.is_now'] = 'no';//不是立即
        }

        $where['order.user_id'] = $this->auth->id;
        $list = model('app\api\model\Order')
            ->with(['address'])
            ->where($where)
            //->where('address.name|address.mobile|address.address|address.idcard','like','%'.$keywords.'%')
            ->order('order.updatetime desc')
            ->paginate();

        foreach ($list as $row) {
            $row->getRelation('address')->visible(['name', 'mobile', 'province', 'city', 'area', 'address', 'idcard', 'idcard_front', 'idcard_reverse', 'zip_code']);
        }
        $this->success('ok', $list);
    }

    /**
     * @throws \think\exception\DbException
     * 添加包裹
     */
    public function createpackage_bak(){
        $data = $this->request->post();
        $ids = $data['ids'];
        if(empty($ids) || !is_array($ids)){

        }

        $user_id = $this->auth->id;
        $packaage_no = orderOn($user_id);
        $packaage_id =  Db::name('express_package')->insertGetId([
            'package_no'=>$packaage_no,
            'user_id'=>$user_id,
            'is_delivery'=>1,
            'status'=>'complete',
            'createtime'=>time(),
            'updatetime'=>time(),
        ]);

        $address = model('app\api\model\Address')->get($data['address_id']);
        if (!$address) {
            $this->error('收货地址不存在');
        }
        $packAddressM = new PackageAddress();

        $packAddress = $packAddressM->get([
            'package_id' => $packaage_id,
            'user_id' => $user_id,
        ]);
        if ($packAddress) {
            $packAddressM->allowField(true)->save([
                'package_id' => $packaage_id,
                'user_id' => $user_id,
                'name' => $address['name'],
                'mobile' => $address['mobile'],
                'province' => $address['province'],
                'city' => $address['city'],
                'area' => $address['area'],
                'address' => $address['address'],
                'zip_code' => $address['zip_code'],
                'province_index' => $address['province_index'],
                'city_index' => $address['city_index'],
                'area_index' => $address['area_index'],
            ]);
        } else {
            $packAddressM = new PackageAddress();$packAddressM->allowField(true)->save([
                'package_id' => $packaage_id,
                'user_id' => $user_id,
                'name' => $address['name'],
                'mobile' => $address['mobile'],
                'province' => $address['province'],
                'city' => $address['city'],
                'area' => $address['area'],
                'address' => $address['address'],
                'zip_code' => $address['zip_code'],
            ]);
        }

        //更新到order_id
        Db::name('express_order')->where('id','in',$ids)->update([
            'package_id'=>$packaage_id,
            'package_no'=>$packaage_no,
        ]);

        $this->success('');
    }

    /**
     * 在仓确定
     * 在仓确定
     */
    public function storeok(){

        $weight = $this->request->param('weight');
        $volume  = $this->request->param('volume');

        $from_express_no = $this->request->post('from_express_no');
        $express_order = Db::name('express_order')->where('from_express_no',$from_express_no)->find();

        $package_no = $express_order['package_no'];
        if($package_no){
            $package_count =  Db::name('express_package')->where(['package_no'=>$package_no])->count();
            if($package_count){
                $this->error('该订单已经有包裹');
            }
        }

        $subscribe = new Subscribe();
       // $template_id = Config::get('site.new_order');
        if($express_order['is_now']=='yes'){
            //成生包裹
            $packaage_no = orderOn($express_order['user_id']);
            $packaage_id =  Db::name('express_package')->insertGetId([
                'package_no'=>$packaage_no,
                'user_id'=>$express_order['user_id'],
                'is_delivery'=>1,
                'status'=>'complete',
                'createtime'=>time(),
                'updatetime'=>time(),
            ]);
            $address_id = Db::name('express_order_address')->where('order_id',$express_order['id'])->value('id');
            $address = model('app\api\model\OrderAddress')->get($address_id);
            if (!$address) {
                $this->error('收货地址不存在');
            }
            $packAddressM = new PackageAddress();
            $packAddress = $packAddressM->get([
                'package_id' => $packaage_id,
                'user_id' => $express_order['user_id'],
            ]);
            if ($packAddress) {
                $packAddressM->allowField(true)->save([
                    'package_id' => $packaage_id,
                    'user_id' => $express_order['user_id'],
                    'name' => $address['name'],
                    'mobile' => $address['mobile'],
                    'province' => $address['province'],
                    'city' => $address['city'],
                    'area' => $address['area'],
                    'address' => $address['address'],
                    'zip_code' => $address['zip_code'],
                    'province_index' => $address['province_index'],
                    'city_index' => $address['city_index'],
                    'area_index' => $address['area_index'],
                ]);
            } else {
                $packAddressM = new PackageAddress();
                $packAddressM->allowField(true)->save([
                    'package_id' => $packaage_id,
                    'user_id' => $express_order['user_id'],
                    'name' => $address['name'],
                    'mobile' => $address['mobile'],
                    'province' => $address['province'],
                    'city' => $address['city'],
                    'area' => $address['area'],
                    'address' => $address['address'],
                    'zip_code' => $address['zip_code'],
                ]);
            }

            Db::name('express_order')->where('from_express_no',$from_express_no)->update([
                'package_no'=>$packaage_no,
                'package_id'=>$packaage_id,
                'status'=>'complete'
            ]);
            $page = 'pages/Packagequery/Packagequery';

        }else{
            $page = 'pages/IndexServer/warehouse/warehouse';
        }

        $template_id = 'dKj4vly11Mg1C-JRd1a9Z9Jl8qPHh2a46D90eSjMEaE';
        //$string = '包裹已入库，重量：'.$weight.'KG，体积重：'.$volume.'KG';
        $data = [
            'character_string1' => [
                'value' => $from_express_no
            ],
            'phrase2' => [
                'value' => "包裹已入库"
            ],
            'thing4' => [
                'value' => "包裹已入库，如未完善快递信息，请立即填写"
            ],
            'time3' => [
                'value' => date("Y-m-d H:i:s")
            ]
        ];
        $subscribe->push($express_order['user_id'], $template_id, $page, $data);
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function packagetrack(){
        $package_id = $this->request->param('package_id');
        $list = Db::name('express_package_track')->where('package_id',$package_id)->order('createtime asc')->select();
        foreach ($list as $key=>$value){
            $list[$key]['createtime'] = date('Y-m-d H:i',$value['createtime']);
            //状态:0=已入库,1=已预报,2=包裹已出库,3=正在发往澳洲,4=包裹清关中,5=包裹清关完成，等待发往指定地点,6=包裹已抵达指定自提点，等待顾客取件,7=已签收
            if($value['state']==0){
                $list[$key]['state_txt'] = '已入库';
            }elseif ($value['state']==1){
                $list[$key]['state_txt'] = '已预报';
            }elseif ($value['state']==2){
                $list[$key]['state_txt'] = '包裹已出库';
            } elseif ($value['state']==3){
                $list[$key]['state_txt'] = '正在发往澳洲';
            }elseif ($value['state']==4){
                $list[$key]['state_txt'] = '包裹清关中';
            }elseif ($value['state']==5){
                $list[$key]['state_txt'] = '包裹清关完成,等待发目的地';
            }elseif ($value['state']==6){
                $list[$key]['state_txt'] = '包裹已抵达目的地，等待顾客取件';
            }elseif ($value['state']==7){
                $list[$key]['state_txt'] = '已签收';
            }
        }
        $this->success('物流轨迹',$list);
    }

    public function is_complete(){
        $from_express_no = $this->request->param('from_express_no');
        $s = Db::name('express_order')->where('from_express_no',$from_express_no)->value('status');
        if($s=='created'){
            $this->success('',0);
        }else{
            $this->success('',1);
        }
    }

    public function yuyuetime(){
        $list = Db::name("yuyue_config")->where(['switch'=>1])->select();
        if(empty($list)){
            $this->success('ok','');
        }
        $date = date("Y-m-d");
        $date_time = strtotime($date);
        $date_list = [];
        foreach ($list as $val){
            if(empty($val['start_date']) || empty($val['end_date'])){
                continue;
            }
            if(empty($val['start_times']) || empty($val['end_times'])){
                continue;
            }
            $start_times = $val['start_times']??"10:00:00";
            $end_times = $val['end_times']??"16:00:00";
            if(strtotime($start_times) > strtotime($end_times)){
                continue;
            }
            $end_times1 = strtotime($end_times);
            $start_times1 = strtotime($start_times);
            $cha_times = $end_times1 - $start_times1;
            $hour = floor($cha_times/3600);
            $yu = $cha_times%3600;
            $min = floor($yu/60);
            $min1 = sprintf("%.2f",$min/60);
            $cha_hour_min_time = sprintf("%.2f",$hour + $min1);
            $start_date_time = strtotime($val['start_date']);
            $end_date_time = strtotime($val['end_date']);
            if($end_date_time<$date_time) continue;
            if($start_date_time>$end_date_time) continue;
            for ($i= $start_date_time;$i<=$end_date_time;$i+=86400){
                $i_date = date("Y-m-d",$i);
                if($i>=$date_time && !isset($date_list[$i_date])){
                    $date_list[$i_date]=['start_times'=>$start_times,'end_times'=>$end_times,'cha_time'=>$cha_hour_min_time,'num'=>$val['num']];
                }
            }
        }
//        dump($date_list);die;
        if(empty($date_list)){
            $this->success('ok','');
        }

        ksort($date_list);
       // $this->success('ok',$date_list);

        $date_time = [];
        $nowTime = time();
        foreach ($date_list as $date_key=>$date_val){
            $w = date("w",strtotime($date_key));
           // $date_time[$date_key]['w'] = $w;
            $stime = strtotime($date_key." ".$date_val['start_times']);
            $entime = strtotime($date_key." ".$date_val['end_times']);
            if($nowTime>$entime) continue;
            if(($entime-$nowTime)<1800) continue;
            if($stime<$nowTime){
              //  $stime = $nowTime;
            }
            $list = [];
            for($j=$stime;$j<$entime;$j+=1800){
                if($j<$nowTime) continue;
                $time_str = date("y-m-d",$j)." ".date("H:i",$j)."-".date("H:i",$j+1800);
                $yuyue_num = Db::name("express_package")->where(['yuyue_sign_time'=>$time_str])->count();
                $list[] = [
                    'time_str'=>$time_str,
                    'num'=>$date_val['num'],
                    'yuyue_num'=>$yuyue_num
                ];
            }
            $date_time[]=[
                'list'=>$list,
                'w'=>$w,
                'num'=>$date_val['num'],
                'date'=>$date_key
            ];
        }

        $this->success('ok',$date_time);
    }

    //首页图片配置
    public function indexImg(){
        $list=[
            "index_1"=>"https://aodatong.akfapp.com/index_img/index_1.png",
            "index_2"=>"https://aodatong.akfapp.com/index_img/index_2.png",
            "index_3"=>"https://aodatong.akfapp.com/index_img/index_3.png",
            "index_4"=>"https://aodatong.akfapp.com/index_img/index_4.png",
            "index_5"=>"https://aodatong.akfapp.com/index_img/index_5.png",
        ];
        $this->success('ok',$list);
    }

    //测试--到仓提醒--有温馨提示
    public function p(){
        //内容
        //https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html#%E8%AE%A2%E9%98%85%E6%B6%88%E6%81%AF%E5%8F%82%E6%95%B0%E5%80%BC%E5%86%85%E5%AE%B9%E9%99%90%E5%88%B6%E8%AF%B4%E6%98%8E
        $str=<<<FOF
详细内容
    订单编号 {{character_string1.DATA}}
    订单状态 {{phrase2.DATA}}
    温馨提示 {{thing4.DATA}}
    操作时间 {{time3.DATA}}
FOF;

        $subscribe = new Subscribe();
        $template_id = 'dKj4vly11Mg1C-JRd1a9Z9Jl8qPHh2a46D90eSjMEaE'; //订单状态更新提醒
        $page = 'pages/Packagequery/Packagequery';
        $user_id = $_GET['user_id']??501;
        $data = [
            'character_string1' => [
                'value' => md5(microtime())
            ],
            'phrase2' => [
                'value' => '包裹已入库'
            ],
            'thing4' => [
                'value' => "包裹已入库，请立即点击进行包裹预报"
            ],
            'time3' => [
                'value' => date('Y-m-d H:i:s')
            ],
        ];
        $res = $subscribe->push($user_id, $template_id, $page, $data);
        dump($res);die;
    }
    //测试--支付提醒
    public function p1(){
        $content = <<<of
详细内容
    运单号
    {{character_string4.DATA}}
    订单金额
    {{amount3.DATA}}
    温馨提示
    {{thing2.DATA}}
of;

        $subscribe = new Subscribe();
        $template_id = '9bQN97-6b-XflU3TrUKS4FSNyr_tM1SdaM6njkuB1p4'; //订单支付提醒
        $page = 'pages/Packagequery/Packagequery';
        $user_id = $_GET['user_id']??501;
        $data = [
            'character_string4' => [
                'value' => md5(microtime())
            ],
            'amount3' => [
                'value' =>"12.36"
            ],
            'thing2' => [
                'value' => "包裹已到达，请支付"
            ],
        ];
        $res = $subscribe->push($user_id, $template_id, $page, $data);
        dump($res);die;
    }
    //测试--到达目的地提醒
    public function p2(){
        $content = <<<of
详细内容
    订单编号
    {{character_string1.DATA}}
    订单状态
    {{phrase2.DATA}}
    操作时间
    {{time3.DATA}}
of;

        $subscribe = new Subscribe();
        $template_id = 'dKj4vly11Mg1C-JRd1a9Zz-U655PjMsskK-WEgLbuC0';  //订单状态更新提醒--无温馨提示
        $page = 'pages/Packagequery/Packagequery';
        $user_id = $_GET['user_id']??501;
        $data = [
            'character_string1' => [
                'value' => md5(microtime())
            ],
            'phrase2' => [
                'value' => '包裹已经到达'
            ],
            'time3' => [
                'value' => date('Y-m-d H:i:s')
            ],
        ];
        $res = $subscribe->push($user_id, $template_id, $page, $data);
        dump($res);die;
    }

    //测试--订单完成通知
    public function p3(){
        $content = <<<of
详细内容
    订单号
    {{character_string1.DATA}}
    完成时间
    {{time2.DATA}}
of;

        $subscribe = new Subscribe();
        $template_id = '2Q6WWQRYmZBOLpLSx38HDaHrP-uY0jLGG3ZQFQN000w';  //物流信息提醒
        $page = 'pages/Packagequery/Packagequery';
        $user_id = $_GET['user_id']??501;
        $data = [
            'character_string9' => [
                'value' => md5(microtime())
            ],
            'thing10' => [
                'value' =>"包裹已到达澳洲"
            ],
            'time11' => [
                'value' => date('Y-m-d H:i:s')
            ],
        ];
        $res = $subscribe->push($user_id, $template_id, $page, $data);
        dump($res);die;
    }
}
